package com.suotuo.module.sys.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * 系统登陆控制器
 * @author liulubingjava@163.com
 * @date 2019/1/29 17:35
 */
@Controller
public class SysLoginController {
    @Autowired
    private Producer producer;

    @GetMapping("captcha.jpg")
    public void getCaptcha(HttpServletResponse response)throws IOException {
        response.setHeader("Cache-Control","no-store, no-cache");
        response.setContentType("image/jpeg");
        //生成文字验证码
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        //保存到shiroSession
        Subject subject = SecurityUtils.getSubject();
        subject.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY,text);
        //输出图片
        ServletOutputStream outputStream = response.getOutputStream();
        ImageIO.write(image,"jpg",outputStream);
    }
}
